//
//  KABCosPubEditTCell.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/8.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosPubEditTCell.h"
#import "SZTextView.h"
#import "KABModel.h"
#import "GlobalHeader.h"


@interface KABCosPubEditTCell()<UITextViewDelegate>
@end

@implementation KABCosPubEditTCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.closeBtn.layer.masksToBounds = YES;
    self.closeBtn.layer.cornerRadius = CGRectGetWidth(self.closeBtn.bounds) / 2.0;
    [self.closeBtn addTarget:self action:@selector(closeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.textView.delegate = self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)closeBtnTapped:(UIButton *)btn {
    if ([self.delegate respondsToSelector:@selector(kABCosPubEditTCell:deleteBtnTapped:)]) {
        [self.delegate kABCosPubEditTCell:self deleteBtnTapped:btn];
    }
}

#pragma mark - <UITextViewDelegate>
- (void)textViewDidChange:(UITextView *)textView {    
    NSString *toBeString = textView.text;
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        if (toBeString.length > KABGlobalCosPubPicDesLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:KABGlobalCosPubPicDesLength];
            if (rangeIndex.length == 1) {
                textView.text = [toBeString substringToIndex:KABGlobalCosPubPicDesLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, KABGlobalCosPubPicDesLength)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
    
    if ([self.delegate respondsToSelector:@selector(kABCosPubEditTCell:textViewDidChanged:)]) {
        [self.delegate kABCosPubEditTCell:self textViewDidChanged:textView];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.item.content = textView.text;
}

- (void)setItem:(KABCosPublishItem *)item {
    _item = item;
    
    self.imgView.image = item.img;
    self.imgViewHeightConstraint.constant = floor([UIScreen mainScreen].bounds.size.width * item.img.size.height /item.img.size.width);
    self.textView.text = item.content;
}

@end

